//
// Created by Administrator on 2021/11/9.
// May Saint Diana bless you!
//
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>

using namespace std;

class Solution {
public:
    int numOfPairs(vector<string> &nums, string target) {
        unsigned int n = nums.size();
        int ans = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                if (i == j)continue;
                if (nums[i] + nums[j] == target)
                    ++ans;
            }
        }
        return ans;
    }
};
class Solution2{
public:
    int numOfPairs(vector<string>& nums, string target) {
        // hashmap 解法
        unordered_map<string, int> m;
        for (auto & num : nums) {
            m[num]++;
        }
        int ans = 0;
        for (int i = 1; i <= target.size(); i++) {
            string t1 = target.substr(0, i);
            string t2 = target.substr(i);
            // printf("%s,%s\n", t1.c_str(), t2.c_str());
            if (t1 == t2) {
                if (m[t1] >= 2) {
                    ans += m[t1] * (m[t1] - 1);
                }
            } else {
                if (m.count(t1) > 0 && m.count(t2) > 0) {
                    ans += m[t1] * m[t2];
                }
            }
        }
        return ans;
    }
};

int main() {
    vector<string> nums{"777", "7", "77", "77"};
    Solution2 solution;
    cout << solution.numOfPairs(nums, "7777");
    return 0;
}
